package com.example.tuter.util;

import com.example.tuter.entity.SchoolCookie;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class CookieUtil {

    public static Map<String, String> parseCookieToMap(String cookieString) {
        if (cookieString == null) return null;
        Map<String, String> cookieMap = new HashMap<>();

        String[] cookieArray = cookieString.split("; ");
        for (String cookie : cookieArray) {
            String[] parts = cookie.split("=");
            String key = parts[0];
            String value = parts.length > 1 ? parts[1] : "";
            cookieMap.put(key, value);
        }

        return cookieMap;
    }

    /**
     * 更新用户的cookie
     *
     * @param cookieMap
     */
    public static void syncUserCookie(Map<String, String> cookieMap) {
        if (cookieMap == null) return;
        if (Constant.schoolCookie == null) Constant.schoolCookie = new SchoolCookie();
        Method[] methods = SchoolCookie.class.getMethods(); // 获取所有方法

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            cookieMap.forEach((s, s2) -> {
                String cookieName = "set" + s;
                for (Method method : methods) {
                    if (cookieName.equalsIgnoreCase(method.getName())) {
                        try {
                            method.invoke(Constant.schoolCookie, s2);
                        } catch (IllegalAccessException | InvocationTargetException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        }
    }

    public static String getCookieFromCookieClass(Object o) {
        Class<?> aClass = o.getClass();
        Method[] methods = aClass.getMethods();
        Field[] fields = aClass.getFields();
        String result = "";
        for (int j = 0; j < fields.length; j++) {
            String name = fields[j].getName();
            String funcName = "get" + name;
            for (Method method : methods) {
                if (funcName.equalsIgnoreCase(method.getName())) {
                    try {
                        String invoke = (String) method.invoke(o);
                        if (invoke != null) {
                            result += name + "=" + invoke + "; ";
                        }

                    } catch (IllegalAccessException | InvocationTargetException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        return result;

    }

    public static boolean checkCookieInKxjs(String htmlString) {
        if ("".equals(htmlString)) return false;
        int i = htmlString.indexOf("同学课表");
        if (i == -1 || htmlString.charAt(i - 2) == '期') return false;
        return true;
    }
}
